import Vue from 'vue'
import Router from 'vue-router'
// 登录
import Login from '@/components/Login'
// 后台首页
import Home from '@/components/Home'
// 后台欢迎页
import Welcome from '@/components/Welcome'
// 用户管理组件
import Users from '@/components/user/Users'
// 权限列表
import Rights from '@/components/power/Rights'
// 角色列表
import Roles from '@/components/power/Roles'
// 商品分类
import Category from '@/components/goods/Category'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    }, // 访问根路径,默认跳转到登录页
    { path: '/login', component: Login },
    // 后台首页,只要访问就进入welcome页
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users },
        { path: '/rights', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/categories', component: Category }
      ]
    }
  ]
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // 访问登录页,直接放行
  if (to.path === '/login') return next()
  // 获取token
  const token = window.sessionStorage.getItem('token')
  // token存在就放行,不存在就跳转登录页
  if (token) return next()
  next('/login')
})
export default router
